package base

import (
	"fmt"
	"math"
	"strconv"
	"strings"
)

type AssetItemId = int32
type AssetItemCount = uint32
type AssetType uint8

const (
	AssetType_Money AssetType = iota + 1
	AssetType_Item
)

const (
	AssetItemMaxCount = math.MaxUint32
)

type AssetItem struct {
	Id     AssetItemId    `json:"itemId"`
	Count  AssetItemCount `json:"num"`
	Entity interface{}
}

func (item *AssetItem) Parse(text string) (err error) {
	const separator = ","
	results := strings.Split(text, separator)

	const minCount = 2
	if len(results) < minCount {
		err = fmt.Errorf("internal item count less than %d", minCount)
		return
	}

	var value int
	var itemId AssetItemId
	if value, err = strconv.Atoi(results[0]); err != nil {
		return
	} else {
		itemId = AssetItemId(value)
	}

	var itemCount AssetItemCount
	if value, err = strconv.Atoi(results[1]); err != nil {
		return
	} else {
		if value < 1 {
			err = fmt.Errorf("item count is %d", value)
			return
		}

		itemCount = AssetItemCount(value)
	}

	item.Id = itemId
	item.Count = itemCount

	return
}

func (item *AssetItem) ToString() (result string) {
	if item.Id < 1 {
		return
	}

	fields := make([]string, 0, 2)
	fields = append(fields, strconv.Itoa(int(item.Id)))
	fields = append(fields, strconv.Itoa(int(item.Count)))

	const separator = ","
	result = strings.Join(fields, separator)
	return
}

func (item *AssetItem) Equal(other *AssetItem) bool {
	return item.Id == other.Id && item.Entity == other.Entity
}

type AssetItems []*AssetItem

func (items AssetItems) Parse(text string) (result AssetItems, err error) {
	const separator = "|"
	rows := strings.Split(text, separator)
	result = make(AssetItems, 0, len(rows))
	for _, row := range rows {
		item := new(AssetItem)
		if err = item.Parse(row); err != nil {
			return
		}
		result = append(result, item)
	}

	return
}

func (items AssetItems) ToString() (result string) {
	length := len(items)
	if length < 1 {
		return
	}

	list := make([]string, 0, length)
	for _, item := range items {
		if text := item.ToString(); text != "" {
			list = append(list, text)
		}
	}

	if len(list) > 0 {
		const separator = "|"
		result = strings.Join(list, separator)
	}

	return
}
